package com.xiaobaibai.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaobaibai.common.OrderCommon;
import com.xiaobaibai.common.OrderEnum;
import com.xiaobaibai.common.WeixinCommon;
import com.xiaobaibai.entity.Order;
import com.xiaobaibai.entity.User;
import com.xiaobaibai.entity.UserInfo;
import com.xiaobaibai.response.ResponseFormat;
import com.xiaobaibai.service.IOrderService;
import com.xiaobaibai.service.ITokenService;
import com.xiaobaibai.service.IUserInfoService;
import com.xiaobaibai.service.IUserService;
import com.xiaobaibai.threadPool.MyThreadPoolUnit;
import com.xiaobaibai.units.pay.HttpClientUnit;
import com.xiaobaibai.units.SecurityUnit;
import com.xiaobaibai.vo.WxUserDetail;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
@Api(tags = "用户类相关接口")
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ITokenService tokenService;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final String WEIXINURL="https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ResponseFormat wxFirstLogin(@RequestBody Map<String,String> map, HttpServletResponse httpServletResponse) {

        //authentication就直接为空

        if (map.get("code")==null)
            return ResponseFormat.failure("请传入code");

        String token=null;

        User user=new User();

        String url = String.format(WEIXINURL, WeixinCommon.APPID,WeixinCommon.SECRET,map.get("code"));

        JSONObject jsonObject = HttpClientUnit.get(url);

        if(jsonObject==null)
            return ResponseFormat.failure("登录失败,网络繁忙");

        String openId=jsonObject.getString("openid");

        if(openId==null)
            return ResponseFormat.failure("登录失败,code错误");

        String session_key=jsonObject.getString("session_key");

        //应该是查
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_openid",openId);
        User one = userService.getOne(queryWrapper);

        if(one==null){//第一次就去注册
            user.setUserOpenid(openId);
            user.setUserSessionKey(session_key);
            user.setUserLastLogin(new Date());

            //默认初始化一下昵称+头像
            user.setUserName("未授权昵称");
            user.setUserImage("http://image.xiaobaibai.ink/%E6%B2%A1%E8%AF%BE.svg");

            userService.save(user);

            //顺便把用户的杂七杂八表给生成了
            UserInfo userInfo=new UserInfo();
            userInfo.setUserId(user.getUserId());
            userInfo.setUserAmount(new BigDecimal(0));
            userInfo.setUserIntegral(0);
            userInfo.setUserOrderQuantity(0);
            userInfoService.save(userInfo);

        }else{//登录
            //刷新新的session_key
            user.setUserId(one.getUserId());
            user.setUserSessionKey(session_key);
            user.setUserLastLogin(new Date());
            userService.updateById(user);
        }
        token = tokenService.getToken(user.getUserId());

        httpServletResponse.setHeader("Authorization",token);
        //应该要返回一个token给客户端
        return ResponseFormat.ok("登录成功",user.getUserId());
    }

    @PostMapping("/addUserInfo")
    public ResponseFormat addUserInfo(@RequestBody WxUserDetail wxUserDetail){
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        //根据security的上下文获取用户的id
        Integer userId= (Integer) authentication.getPrincipal();

        stringRedisTemplate.delete("getDetailByUserId-"+userId);//删除个人信息缓存

        User user=new User();
        user.setUserId(userId);
        user.setUserImage(wxUserDetail.getAvatarUrl());
        user.setUserName(wxUserDetail.getNickName());
        user.setUserGender(wxUserDetail.getGender()==1);
        userService.updateById(user);

        return ResponseFormat.ok("保存用户信息成功");
    }

    @GetMapping("/me")
    @ApiOperation("'我的界面'数据接口")
    public ResponseFormat getMeData() throws ExecutionException, InterruptedException {
        Integer userId = SecurityUnit.getUserId();
        /**
         * 用户头像+用户id+昵称
         * 待评价订单数量(已完成)->用缓存来存入用户近期15天完成的订单,如果用户评价后去掉缓存里的订单号即可
         * 待付款订单数量(待支付状态)+待收货订单数量(货到付款+等待送达)+售后订单数量(取消中)
         */
        Map<String,Object> map=new HashMap<>();
        CompletableFuture<Void> c1 = CompletableFuture.runAsync(() -> {
            QueryWrapper<Order> q1 = new QueryWrapper<>();
            q1.eq("user_id", userId);
            q1.eq("order_status", OrderEnum.NOPAY.getCode());
            int waitPayOrder = orderService.count(q1);//待支付状态订单

            QueryWrapper<Order> q2 = new QueryWrapper<>();
            q2.eq("user_id", userId);
            q2.in("order_status", OrderEnum.ING.getCode());
            int ingCount = orderService.count(q2);//等待送达状态订单

            QueryWrapper<Order> q3 = new QueryWrapper<>();
            q3.eq("user_id", userId);
            q3.in("order_status", OrderEnum.CANCELING.getCode());
            int cancelIngCount = orderService.count(q3);//取消中状态订单

            map.put("waitPayOrder", waitPayOrder);
            map.put("ingCount", ingCount);
            map.put("cancelIngCount", cancelIngCount);
        }, MyThreadPoolUnit.threadPoolExecutor);

        Long waitEvaluation =
                stringRedisTemplate.opsForList().size(OrderCommon.waitEvaluationOrder + userId);//等待评价订单
        map.put("waitEvaluation",waitEvaluation);

        User user = userService.getDetailByUserId(userId);
        user.setUserId(user.getUserId()+10000);//故意加这么多,显的用户多
        map.put("user",user);

        //查询用户积分
        QueryWrapper<UserInfo> q2=new QueryWrapper<>();
        q2.select("user_integral","user_amount");//查询用户积分
        q2.eq("user_id",userId);
        UserInfo userInfo = userInfoService.getOne(q2);
        map.put("userIntegral",userInfo.getUserIntegral());//存入用户积分
        map.put("userAmount",userInfo.getUserAmount());//存入用户消费金额

        CompletableFuture<Void> all = CompletableFuture.allOf(c1);
        all.get();//等待

        return ResponseFormat.ok("我的页面消息获取成功",map);
    }

}
